package cn.livingCloud.controller.user.validator;

import cn.livingCloud.dto.ChangePasswordDto;
import cn.livingCloud.service.UserAccountService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Created by 唐旭 on 2016/1/14.
 */
@Component
public class ChangePasswordDtoValidator implements Validator {
    @Qualifier("userAccountServiceImpl")
    @Autowired
    private UserAccountService service;

    @Override
    public boolean supports(Class<?> aClass) {
        return ChangePasswordDto.class.equals(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ChangePasswordDto passwordDto = (ChangePasswordDto) o;
        validateOldPassword(passwordDto, errors);
        validateNewPassword(passwordDto, errors);
    }

    private void validateNewPassword(ChangePasswordDto passwordDto, Errors errors) {
        String confirmPassword = passwordDto.getConfirmPassword();
        String newPassword = passwordDto.getNewPassword();
        if (StringUtils.isEmpty(newPassword)) {
            errors.rejectValue("newPassword", null, "新密码不能为空");
            return;
        }
        if (StringUtils.isEmpty(confirmPassword)) {
            errors.rejectValue("confirmPassword", null, "确认密码不能为空");
            return;
        }
        if (!confirmPassword.equals(newPassword)) {
            errors.rejectValue("newPassword", null, "两次输入的密码不一致");
        }
    }

    private void validateOldPassword(ChangePasswordDto passwordDto, Errors errors) {
        String oldPassword = passwordDto.getOldPassword();
        boolean result = service.checkPassword(oldPassword);
        if (!result) {
            errors.rejectValue("oldPassword", null, "旧密码错误!");
        }
    }
}
